const { exec } = require('child_process');
const fs = require('fs');
const path = require('path');

// 日志文件路径
const logPath = path.join(__dirname, 'server_log.txt');

console.log(`启动服务器并将日志输出到: ${logPath}`);

// 执行npm start命令并捕获输出
const child = exec('npm start', { cwd: __dirname });

// 记录标准输出
child.stdout.on('data', (data) => {
  fs.appendFileSync(logPath, data);
  console.log(data.toString());
});

// 记录错误输出
child.stderr.on('data', (data) => {
  fs.appendFileSync(logPath, data);
  console.error(data.toString());
});

// 记录退出事件
child.on('close', (code) => {
  const exitMsg = `服务器进程退出，退出码: ${code}\n`;
  fs.appendFileSync(logPath, exitMsg);
  console.log(exitMsg);
});